#include "LCD_Drive.h"

/*
*@brief This function will test the busy flag, it
*won't quit until the flag is 0
*@param None
*@retval None
*/
void LCD_busy_check(void){
	bit state = 0;
	
	trisd = 0b11111111;
	
	clear_bit(portc,RS);
	set_bit(portc,RW);
	
	do{
		set_bit(portc,E);
		state = test_bit(portd,D7);
		//delay_ms(5);
		clear_bit(portc,E);
	}while(state == 1);
	
	trisd = 0b00000000;
}


void LCD_write_CMD(unsigned char comm){
	LCD_busy_check();
	clear_bit(portc,RS);
	clear_bit(portc,RW);
	portd = comm;
	set_bit(portc,E);
	delay_ms(5);
	clear_bit(portc,E);
}

void LCD_write_DAT(unsigned char dat){
	LCD_busy_check();
	set_bit(portc,RS);
	clear_bit(portc,RW);
	portd = dat;
	set_bit(portc,E);
	delay_ms(5);
	clear_bit(portc,E);
}

void LCD_init(void){
	trisd = 0b00000000;
	trisc = 0b10001111;
	LCD_write_CMD(0b00111000);
	LCD_write_CMD(0b00001100);
	LCD_write_CMD(0b00000110);
	LCD_write_CMD(0b00000001);
}

void LCD_disp_line1(char* strings){
	for(int i=0;strings[i]!='\0';i++){
		LCD_write_DAT(strings[i]);
	}
}

void LCD_disp_line2(char* strings){
	LCD_write_CMD(0x40|0x80);
	for(int i=0;strings[i]!='\0';i++){
		LCD_write_DAT(strings[i]);
	}
}

void LCD_set_cursor(unsigned char x, unsigned char y)
{
	unsigned char addr=0x00;
	
	if (y == 0){
		addr = 0x00 + x;
	}
	else{
		addr = 0x40 + x;
	}
	LCD_write_CMD(addr | 0x80);
}

void LCD_Clear(void){
	LCD_write_CMD(0b00000001);
}